<template>
    <div>
        <!-- 搜索表单区域 -->
        <common-form ref="searchFormRef" inline :form="searchForm" :formLabel="searchFormLabel">
            <el-button type="primary" icon="el-icon-search" size="mini" @click="searchCate">搜索</el-button>
            <el-button  icon="el-icon-refresh" size="mini" @click="resetCate">重置</el-button>
        </common-form>
        <!-- 操作按钮区域 -->
        <div >
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="addDialog">新增</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="disAbled" @click="delSelect">删除</el-button>
            <!-- 导出 excel 表格 -->
            <el-popover
              placement="top"
              width="200"
              style="margin-left:10px;">
              <p style="font-size:13px;"><i class="el-icon-s-opportunity" style="color: green;"></i> 请选择你所需要导出的类型！</p>
              <div style="text-align: right; margin: 0">
                  <export-excel Type="info" :excelData="allSelection" :excelTitle="excelTitle" :excelHeader="excelHeader" :excelVal="excelVal">全部</export-excel>
                  <export-excel Type="success" :excelData="multipleSelection" :excelTitle="excelTitle" :excelHeader="excelHeader" :excelVal="excelVal">选中项</export-excel>
              </div>
              <el-button slot="reference" type="warning" size="mini" icon="el-icon-s-data" @click="exlAll()">EXCEL</el-button>
            </el-popover>
        </div>
        <!-- 表格区域 -->
        <common-table
            :tableData="cateTable" :tableLabel="cateTableLabel" :config="config"
            @changeSize="changeSize" @changeCurrent="changeCurrent"
            @changeStatus="changeStatus" @edit="eidtDialog" @del="delCate"
            @changeSelect="changeSelect">
        </common-table>

        <!-- Dialog区域 -->
        <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="25%" @close="closeDialog">
          <el-row>
            <el-col :span="18">
              <common-form :form="dialogForm" :formLabel="dialogFormLable">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button v-if="dialogTitle==='添加分类'" type="primary" @click="addCate">添 加</el-button>
                <el-button v-else type="primary" @click="editCate">修 改</el-button>
              </common-form>
            </el-col>
          </el-row>
        </el-dialog>
    </div>
</template>

<script>
import CommonForm from '../../components/CommonForm'
import CommonTable from '../../components/CommonTable'
import ExportExcel from '../../components/ExportExcel'

export default {
  components: {
    CommonForm,
    CommonTable,
    ExportExcel
  },
  data () {
    return {
      // 搜索表单
      searchForm: {
        name: '',
        status: '',
        date: ''
      },
      // 搜索表单label
      searchFormLabel: [
        {
          model: 'name',
          label: '分类名',
          type: 'input'
        },
        {
          model: 'status',
          label: '状态',
          type: 'select',
          opts: [
            {
              value: '',
              label: '全部'
            },
            {
              value: 1,
              label: '正常'
            },
            {
              value: 2,
              label: '弃用'
            }
          ]
        },
        {
          model: 'date',
          label: '时间',
          type: 'date'
        }
      ],
      // 商品分类表格数据
      cateTable: [],
      // 商品分类展示内容,
      cateTableLabel: [
        {
          prop: 'name',
          label: '分类名'
        },
        {
          prop: 'num',
          label: '商品数量'
        },
        {
          prop: 'status',
          label: '状态',
          type: 'switch'
        },
        {
          prop: 'createTime',
          label: '创建时间'
        }
      ],
      // table配置对象
      config: {
        loading: false,
        current: 0,
        size: 0,
        total: 0,
        btn: [
          {
            type: ''
          },
          {
            type: 'edit'
          },
          {
            type: 'delete'
          }
        ]
      },
      // 请求页面参数
      pageConfig: {
        name: '',
        status: '',
        leftTime: '',
        rightTime: '',
        condition: '',
        current: 1,
        size: 5
      },
      // 控制按钮是否可用
      disAbled: true,
      // 选中表格数据返回数组
      multipleSelection: [],
      // 导出表格的所有数据缓存
      allSelection: [],
      // 自定义导出 excel 表头
      excelHeader: ['分类名', '商品数量', '状态', '创建时间', '更新时间'],
      // 自定义导出 excel 字段
      excelVal: ['name', 'num', 'statusLabel', 'createTime', 'updateTime'],
      // 自定义导出 excel 文件名
      excelTitle: '商品分类',

      // 添加分类参数
      addForm: {
        code: '', // 默认可用状态
        name: ''
      },
      addFormLabel: [
        {
          model: 'code',
          label: '状态',
          type: 'select',
          opts: [
            {
              value: '1',
              label: '正常'
            },
            {
              value: '2',
              label: '弃用'
            }
          ]
        },
        {
          model: 'name',
          label: '分类名',
          type: 'input'
        }
      ],
      editForm: {
        id: '',
        name: ''
      },
      editFormLabel: [
        {
          model: 'name',
          label: '分类名',
          type: 'input'
        }
      ],
      // dialog参数设置
      dialogTitle: '',
      dialogVisible: false,
      dialogForm: {},
      dialogFormLable: []
    }
  },
  methods: {
    // 获取分类列表
    async getCateList () {
      this.config.loading = true
      const { data: res } = await this.$http.post('/category/page', this.pageConfig)
      console.log('商品分类', res)
      if (res.code !== 200) {
        this.config.loading = false
        return this.$message.error('获取商品分类列表失败！')
      }
      // 商品列表赋值
      const result = res.data
      this.cateTable = result.list.map(item => {
        if (item.status === 1) {
          item.status = true
        } else {
          item.status = false
        }
        return item
      })
      this.config.total = result.total
      this.config.current = result.current
      this.config.size = result.size
      this.config.loading = false
    },
    changeSize (size) {
    //   console.log(`每页${size}条`)
      this.pageConfig.size = size
      this.getCateList()
    },
    changeCurrent (current) {
    //   console.log(`当前页：${current}`)
      this.pageConfig.current = current
      this.getCateList()
    },
    // 改变状态
    async changeStatus (row) {
      const { data: res } = await this.$http('/category/update-status', {
        params: {
          code: row.status ? 1 : 2,
          id: row.id
        }
      })
      // console.log('改变status', res)
      if (res.code !== 200) {
        return this.$message.error('状态改变失败！')
      }
      this.$message.success('状态改变成功！')
      this.getCateList()
    },
    // 点击搜索返回表单数据
    searchCate () {
      var form = this.$refs.searchFormRef.form
      this.pageConfig.name = form.name
      if (form.status !== '') {
        this.pageConfig.status = form.status
      } else {
        this.pageConfig.status = ''
      }
      if (form.date) {
        this.pageConfig.leftTime = form.date[0]
        this.pageConfig.rightTime = form.date[1]
        this.pageConfig.condition = 0
      } else {
        this.pageConfig.leftTime = this.pageConfig.rightTime = this.pageConfig.condition = ''
      }
      // console.log('子', form)
      // console.log('请求参数', this.pageConfig)
      this.getCateList()
    },
    // 点击重置表单数据
    resetCate () {
      // this.searchForm = this.$refs.searchFormRef.form
      for (const key in this.pageConfig) {
        if (key !== 'current' && key !== 'size') { this.pageConfig[key] = '' }
      }
      for (const key in this.searchForm) {
        this.searchForm[key] = ''
      }
      this.getCateList()
    },
    // 打开添加分类dialog
    addDialog () {
      this.dialogTitle = '添加分类'
      this.dialogForm = this.addForm
      this.dialogFormLable = this.addFormLabel
      this.dialogVisible = true
    },
    // 添加分类
    async addCate () {
      const { data: res } = await this.$http.get('/category/insert', { params: this.addForm })
      console.log('添加分类', res)
      if (res.code !== 200) {
        return this.$message.error('添加分类失败！')
      }
      this.$message.success('添加分类成功！')
      this.getCateList()
      this.dialogVisible = false
    },
    // 关闭添加分类对话框
    closeDialog () {
      for (const key in this.dialogForm) {
        this.addForm[key] = ''
      }
    },
    // 打开编辑分类dialog
    eidtDialog (row) {
      // 赋值展示
      this.editForm.id = row.id
      this.editForm.name = row.name

      this.dialogTitle = '编辑分类'
      this.dialogForm = this.editForm
      this.dialogFormLable = this.editFormLabel
      this.dialogVisible = true
    },
    // 编辑分类
    async editCate () {
      // console.log('编辑分类', this.editForm)
      const { data: res } = await this.$http.get('/category/update-name', { params: this.editForm })
      if (res.code !== 200) {
        return this.$message.error('修改分类名失败！')
      }
      this.$message.success('修改分类成功！')
      this.getCateList()
      this.dialogVisible = false
    },
    // 删除分类
    delCate (row) {
      this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.get(`/category/delete/${row.id}`)
        if (res.code !== 200) {
          return this.$message.error('删除分类失败！')
        }
        this.$message.success('删除分类成功！')
        this.getCateList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 删除选中项
    delSelect () {
      this.$confirm(`此操作将永久删除 ${this.multipleSelection.length} 条分类, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // 获取id数组
        var delArr = this.multipleSelection.map(item => {
          return item.id
        })
        for (var i in delArr) {
          var id = Number(delArr[i])
          // console.log(id)
          const { data: res } = await this.$http.get(`/category/delete/${id}`)
          // console.log(res)
          if (res.code !== 200) {
            return this.$message.error('删除分类失败！')
          }
        }

        this.$message.success(`已成功删除条 ${delArr.length} 分类成功！`)
        this.getCateList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 表格选择获取数据
    changeSelect (val) {
      this.multipleSelection = val.map(item => {
        item.statusLabel = item.status === true ? '正常' : '弃用'
        return item
      })
      // console.log(this.multipleSelection)
      // 如果选择数据大于 0 则固定按钮可使用
      if (this.multipleSelection.length > 0) {
        this.disAbled = false
      } else {
        this.disAbled = true
      }
    },
    // 导出全部
    async exlAll () {
      var queryInfo = {
        name: '',
        status: '',
        leftTime: '',
        rightTime: '',
        condition: '',
        current: 1,
        size: this.config.total
      }
      const { data: res } = await this.$http.post('/category/page', queryInfo)
      if (res.code !== 200) {
        return this.$message.error('获取商品分类列表失败！')
      }
      // 商品列表赋值
      const result = res.data
      this.allSelection = result.list.map(item => {
        item.statusLabel = item.status === 1 ? '正常' : '弃用'
        return item
      })
    }
  },
  created () {
    this.getCateList()
  }

  // 父组件主动获取子组件数据
  // this.$refs.组件ref.属性
  // this.$refs.组件ref.方法
  // 子组件主动获取父组件的数据和方法
  // this.$parent.数据
  // this.$parent.方法
}
</script>

<style lang="scss" scoped>

</style>
